package com.livedocumentation.client.web.menu;

import java.util.ArrayList;
import java.util.Arrays;

import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.livedocumentation.client.GWTEntryPoint;
import com.livedocumentation.client.model.ProjectClass;
import com.livedocumentation.client.model.Feature;

public class UserInterfaceList extends Tree {

	private static TreeItem cleanedRoot = new TreeItem();

	public UserInterfaceList(ArrayList<ProjectClass> entries) {

		TreeItem root = new TreeItem("");

		if (entries != null) {

			TreeItem parent = root;

			ProjectClass[] features = getSortedArray(entries);

			for (ProjectClass feature : features) {

				if (showFeature(feature)) {

					String[] featurePath = feature.toString().split("\\.");

					parent = root;

					for (int i = 0; i < featurePath.length - 1; i++) {

						String itemName = "<font size=1>"
								+ "<img src='/images/folder-open.gif'> "
								+ featurePath[i] + "</font>";

						Integer childIndex = hasChild(parent, " "
								+ featurePath[i]);

						if (childIndex == null) {

							TreeItem node = new TreeItem(itemName);

							parent.addItem(node);

							node.setState(true);

							parent = node;

						} else {

							parent = parent.getChild(childIndex);
						}
					}

					TreeItem node = new TreeItem(new AnchorFileName(feature));

					parent.addItem(node);

					parent.setState(true);
				}
			}

			cleanedRoot = root;

			cleanTree(root);

			cleanedRoot.setHTML(GWTEntryPoint.currentProject.getName());

			cleanedRoot.setState(true);

			openStates(cleanedRoot);

		}

		this.addItem(cleanedRoot);
	}

	private static void openStates(TreeItem item) {

		for (int i = 0; i < item.getChildCount(); i++) {

			item.getChild(i).setState(true);

			openStates(item.getChild(i));
		}
	}

	private static void cleanTree(TreeItem root) {

		if (root.getChildCount() == 1) {

			cleanedRoot = root.getChild(0);

			cleanTree(cleanedRoot);
		}
	}

	private static boolean showFeature(Feature projectFeature) {

		if (Feature.FEATURE_TYPE.equals(projectFeature.getFeatureType())
				|| Feature.USER_INTERFACE_TYPE.equals(projectFeature
						.getFeatureType())) {

			return true;

		}

		return false;
	}

	private static Integer hasChild(TreeItem item, String itemName) {

		for (int j = 0; j < item.getChildCount(); j++) {

			if (item.getChild(j).getText().equals(itemName)) {

				return j;
			}
		}

		return null;
	}

	public static ProjectClass[] getSortedArray(
			ArrayList<ProjectClass> featuresMap) {

		ProjectClass[] entries = new ProjectClass[featuresMap.size()];

		featuresMap.toArray(entries);

		Arrays.sort(entries);

		return entries;
	}
}
